-- 资源池
local ResPool = class("ResPool")
local GameUtils = require("utils.GameUtils")

function ResPool:ctor(resPath, poolManager, key)
    self._poolManager = poolManager
    self._resPath = resPath
    self._objectList = {}
    self.isDestroy = false
    self._key = key
end

function ResPool:getResObject(parent)
    if #self._objectList == 0 then
        local prefabs = G_ResourceManager:loadPrefabs(self._resPath)
        local object = GameUtils.instantiate(prefabs, parent)
        return object, false
    end
    local len = #self._objectList
    local object = self._objectList[len]
    if object.transform.parent then
        local count = object.transform.parent.childCount
        object.transform:SetSiblingIndex(count - 1)
    end
    object:SetActive(true)
    table.remove(self._objectList, len)
    return object, true
end

function ResPool:recycleObject(object)
    if self.isDestroy then
        return
    end
    object:SetActive(false)
    local luaBehaviour = object:GetComponent(typeof(CS.LuaBehaviour))
    if luaBehaviour then
        luaBehaviour:ClearScriptEnv()
    end
    table.insert(self._objectList, object)
end

function ResPool:destroy(noRemove)
    self.isDestroy = true
    for i = 1, #self._objectList do
        GameUtils.destroy(self._objectList[i])
    end
    self._objectList = {}
    if not noRemove then
        self._poolManager:removeResPool(self._key)
    end
end

return ResPool
